package com.jumi.microservice.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jumi.microservice.common.constant.ResultEnum;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.common.redis.RedisCache;
import com.jumi.microservice.constant.*;
import com.jumi.microservice.domain.SourceMaterialDO;
import com.jumi.microservice.domain.SourceMaterialDTO;
import com.jumi.microservice.mapper.SourceMaterialMapper;
import com.jumi.microservice.service.SourceMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * <p>
 * 商城素材表 服务实现类
 * </p>
 *
 * @author liuz
 * @since 2020-07-27
 */
@Service
@Transactional
public class SourceMaterialServiceImpl extends ServiceImpl<SourceMaterialMapper, SourceMaterialDO> implements SourceMaterialService {

    @Autowired
    private RedisCache redisCache;

    /**
     * 添加商城素材
     *
     * @param dto
     */
    @Override
    public void insert(SourceMaterialDTO dto) {
        SourceMaterialDO sourceMaterial = dto2Po(dto);
        ExceptionEnum.FAIL_SOURCE_NULL.doThrowIf(sourceMaterial == null);
        LocalDateTime now = LocalDateTime.now();
        sourceMaterial.setCreateTime(now);
        sourceMaterial.setUpdateTime(now);
        int insertById = baseMapper.insert(sourceMaterial);

        if (insertById > NumberConstant.NUMBER_ZERO.intValue()) {
            if (redisCache.hasObjectByKey(GoodsKeyConstant.GOODS_DETAIL_KEY + sourceMaterial.getSpuGoodsId())) {
                redisCache.deleteObject(GoodsKeyConstant.GOODS_DETAIL_KEY + sourceMaterial.getSpuGoodsId());
            }
        }
    }

    /**
     * (批量)删除商城素材
     *
     * @param ids      主键id
     * @param username 用户名
     */
    @Override
    public void deleteByIds(String ids, String username) {
        ExceptionEnum.FAIL_ID_NULL.doThrowIf(ids == null);
        String[] idss = ids.split(",");
        Arrays.stream(idss).forEach(id -> {
            SourceMaterialDO source = baseMapper.selectById(id);
            if (source != null && source.getStatus() == StatusEnum.STATUS_YES.getCode()) {
                throw new BaseException(new IResponseRxceptionCode(ResultEnum.FAIL.getCode(), StrUtil.format(ExceptionEnum.FAIL_STATUS_SOURCE.getMessage(), source.getId())));
            }
            source.setIsDel(StatusEnum.STATUS_YES.getCode());
            source.setUpdateTime(LocalDateTime.now());
            source.setModifier(username);
            int updateById = baseMapper.updateById(source);

            if (updateById > NumberConstant.NUMBER_ZERO.intValue()) {
                if (redisCache.hasObjectByKey(GoodsKeyConstant.GOODS_DETAIL_KEY + source.getSpuGoodsId())) {
                    redisCache.deleteObject(GoodsKeyConstant.GOODS_DETAIL_KEY + source.getSpuGoodsId());
                }
            }
        });
    }

    /**
     * 更新商城素材
     *
     * @param dto
     */
    @Override
    public void updateSm(SourceMaterialDTO dto) {
        SourceMaterialDO sourceMaterialDO = baseMapper.selectById(dto.getId());
        Long spuGoodsId = sourceMaterialDO.getSpuGoodsId();

        SourceMaterialDO sourceMaterial = dto2Po(dto);
        ExceptionEnum.FAIL_SOURCE_NULL.doThrowIf(sourceMaterial == null);
        sourceMaterial.setUpdateTime(LocalDateTime.now());
        int updateById = baseMapper.updateById(sourceMaterial);

        if (updateById > NumberConstant.NUMBER_ZERO.intValue()) {
            if (redisCache.hasObjectByKey(GoodsKeyConstant.GOODS_DETAIL_KEY + sourceMaterial.getSpuGoodsId())) {
                redisCache.deleteObject(GoodsKeyConstant.GOODS_DETAIL_KEY + sourceMaterial.getSpuGoodsId());
            }

            if (!spuGoodsId.equals(dto.getSpuGoodsId())) {
                //编辑素材时更新了绑定到的商品，要把原来的商品缓存也要删除
                if (redisCache.hasObjectByKey(GoodsKeyConstant.GOODS_DETAIL_KEY + spuGoodsId)) {
                    redisCache.deleteObject(GoodsKeyConstant.GOODS_DETAIL_KEY + spuGoodsId);
                }
            }
        }
    }

    /**
     * 获取素材详情
     *
     * @param id 主键id
     * @return
     */
    @Override
    public SourceMaterialDTO selectById(Long id) {
        ExceptionEnum.FAIL_SOURCE_NULL.doThrowIf(id == null);
        return po2Dto(baseMapper.selectById(id));
    }

    /**
     * 素材启用/禁用
     *
     * @param id       主键id
     * @param status   状态，1启用，0.禁用
     * @param username 操作用户名
     */
    @Override
    public void enableStatus(Long id, Integer status, String username) {
        ExceptionEnum.FAIL_SOURCE_NULL.doThrowIf(id == null);
        SourceMaterialDO po = baseMapper.selectById(id);
        ExceptionEnum.FAIL_SOURCE_NULL.doThrowIf(po == null);
        po.setModifier(username);
        po.setUpdateTime(LocalDateTime.now());
        po.setStatus(status);
        int updateById = baseMapper.updateById(po);

        if (updateById > NumberConstant.NUMBER_ZERO.intValue()) {
            if (redisCache.hasObjectByKey(GoodsKeyConstant.GOODS_DETAIL_KEY + po.getSpuGoodsId())) {
                redisCache.deleteObject(GoodsKeyConstant.GOODS_DETAIL_KEY + po.getSpuGoodsId());
            }
        }
    }

    /**
     * dto->vo
     *
     * @param dto
     * @return
     */
    private SourceMaterialDO dto2Po(SourceMaterialDTO dto) {
        SourceMaterialDO po = null;
        try {
            po = dto.clone(SourceMaterialDO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return po;
    }

    /**
     * po->dto
     *
     * @param po
     * @return
     */
    private SourceMaterialDTO po2Dto(SourceMaterialDO po) {
        SourceMaterialDTO dto = null;
        try {
            dto = po.clone(SourceMaterialDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return dto;
    }
}
